using System;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Uow;
using Volo.Abp.Domain.Services;
using Volo.Abp.EventBus.Distributed;
using Joy.Erp.BasicArchives.Core.Events;

namespace Joy.Erp.BasicArchives.Suppliers
{
    public class SupplierTypeManager : DomainService
    {
        protected ISupplierTypeRepository SupplierTypeRepository => LazyServiceProvider.LazyGetRequiredService<ISupplierTypeRepository>();
        protected IDistributedEventBus DistributedEventBus => LazyServiceProvider.LazyGetRequiredService<IDistributedEventBus>();

        [UnitOfWork]
        public async Task<SupplierType> CreateAsync(SupplierType entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            entity.SetId(GuidGenerator.Create());
            entity.TenantId = CurrentTenant.Id;

            await DistributedEventBus.PublishAsync(new EntityCreatingEto<SupplierType>(entity), false);
            return await SupplierTypeRepository.InsertAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task<SupplierType> UpdateAsync(SupplierType entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            await DistributedEventBus.PublishAsync(new EntityUpdatingEto<SupplierType>(entity), false);
            return await SupplierTypeRepository.UpdateAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task DeleteAsync(Guid id, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            var entity = await SupplierTypeRepository.GetAsync(id);

            await DistributedEventBus.PublishAsync(new EntityDeletingEto<SupplierType>(entity), false);
            await SupplierTypeRepository.DeleteAsync(entity, autoSave, cancellationToken);
        }
    }
} 